
const valid = (value: any) => {
  if (Array.isArray(value) && !value.length) {
    return false;
  } else if (!value && value !== 0 && value !== false) {
    return false;
  }
  return true;
};

// 过滤参数无效字段
export function getValidKey(object: { [key: string]: any }) {
  const data: { [key: string]: any } = {};
  for (const key in object) {
    const value = object[key];
    if (valid(value)) {
      data[key] = value;
    }
  }
  return data;
}

interface Options {
  // 初始化搜索条件
  filters?: any;
  pagination?: {
    pageNum: number,
    pageSize: number,
  };
  requestAuto?: boolean
}

const defaultOptions = {
  filters: {},
  requestAuto: true
}

export function useTable(
  requestApi: (par: any) => Promise<any> | any,
  params: any,
  options: Options
) {
  options = {
    ...defaultOptions,
    ...options
  }

  // 加载状态
  const loading = ref(false);
  function setLoading(value: boolean) {
    loading.value = value;
  }
  const state = reactive({
    // 列表数据源
    tableData: [],
    // 搜索条件
    searchInfo: {},
    // 分页
    pagData: {
      pageNum: 1,
      pageSize: 10,
      total: 0
    }
  });
  // 初始化查询条件
  function initSearchInfo() {
    state.searchInfo = options.filters;
  }
  function setPag(value: any) {
    state.pagData = {
      ...state.pagData,
      ...value
    };
  }
  // 初始化请求参数
  function initRequestParam() {
    initSearchInfo()
    const { pagination} = options
    if (pagination) {
      setPag(pagination);
    }
  }
  // 获取请求参数
  function getRequestParam() {
    const { searchInfo, pagData } = state
    const { pageNum, pageSize } = pagData;
    return {
      ...getValidKey(searchInfo),
      pageNum,
      pageSize,
      ...params,
    };
  }
  // 查询表格
  async function handleRequest() {
    if (typeof requestApi !== "function") return;
    setLoading(true);
    const reqParams = getRequestParam();
    const res = await requestApi(reqParams);
    if (res) {
      const { list = [], total } = res;
      state.tableData = list
      setPag({ total });
    }
    setLoading(false);
  }

  // 初始化请求
  onMounted(() => {
    initRequestParam();
    if (options.requestAuto) {
      handleRequest();
    }
  });

  // 监听传入参数变化，重新获取数据
  watch(params, handleRequest, { deep: true });

  // 点击查询
  function handleSearch() {
    setPag({ pageNum: 1 });
    handleRequest();
  }
  // 重置查询条件
  function handleReset() {
    initSearchInfo();
    handleRequest();
  }
  function handleSizeChange(pageSize: number) {
    setPag({ pageNum: 1, pageSize });
    handleRequest();
  }
  function handleCurrentChange(pageNum: number) {
    setPag({ pageNum });
    handleRequest();
  }
  // 刷新表格
  function refresh() {
    handleRequest();
  }
  // 刷新表格,重置所有查询条件
  function reload() {
    initRequestParam();
    handleRequest();
  }

  return {
    loading,
    state,
    refresh,
    reload,
    handleSearch,
    handleReset,
    handleSizeChange,
    handleCurrentChange,
  }
}
